<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { message } from 'ant-design-vue';

interface Props {
  visible: boolean;
  application: any;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'saved'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const activeTab = ref('basic');
const saving = ref(false);
const basicFormRef = ref();
const resourceFormRef = ref();

// 基础配置
const basicConfig = reactive({
  name: '',
  version: '',
  description: '',
  environment: 'prod',
  region: 'cn-hangzhou',
});

// 资源配置
const resourceConfig = reactive({
  cpu: 2,
  memory: 4,
  storage: 50,
  domain: '',
  port: 80,
  replicas: 1,
  autoScale: false,
});

// 环境变量
const envVars = ref([
  { id: 1, key: 'NODE_ENV', value: 'production', description: '运行环境' },
  { id: 2, key: 'DB_HOST', value: 'localhost', description: '数据库主机' },
  { id: 3, key: 'REDIS_HOST', value: 'localhost', description: 'Redis主机' },
]);

// 功能开关
const features = ref([
  { key: 'auth', name: '用户认证', enabled: true, required: true },
  { key: 'payment', name: '支付功能', enabled: true, required: false },
  { key: 'notification', name: '消息通知', enabled: true, required: false },
  { key: 'analytics', name: '数据分析', enabled: false, required: false },
  { key: 'backup', name: '数据备份', enabled: true, required: false },
  { key: 'monitoring', name: '系统监控', enabled: true, required: false },
]);

const advancedFeatures = ref([
  { key: 'ssl', name: 'SSL证书', enabled: true },
  { key: 'cdn', name: 'CDN加速', enabled: false },
  { key: 'loadbalancer', name: '负载均衡', enabled: false },
  { key: 'autoscaling', name: '自动扩缩容', enabled: false },
  { key: 'backup', name: '自动备份', enabled: true },
  { key: 'logging', name: '日志收集', enabled: true },
]);

// 环境变量表格列
const envVarColumns = [
  { title: '变量名', dataIndex: 'key', key: 'key', width: 150 },
  { title: '变量值', dataIndex: 'value', key: 'value', width: 200 },
  { title: '描述', dataIndex: 'description', key: 'description' },
  { title: '操作', key: 'action', width: 80 },
];

// 表单验证规则
const basicRules = {
  version: [{ required: true, message: '请输入版本号' }],
  environment: [{ required: true, message: '请选择运行环境' }],
  region: [{ required: true, message: '请选择部署区域' }],
};

const resourceRules = {
  cpu: [{ required: true, message: '请设置CPU核心数' }],
  memory: [{ required: true, message: '请设置内存大小' }],
  storage: [{ required: true, message: '请设置存储大小' }],
};

// 监听应用数据变化
watch(
  () => props.application,
  (app) => {
    if (app) {
      // 加载应用配置
      loadApplicationConfig(app);
    }
  },
  { immediate: true },
);

// 加载应用配置
const loadApplicationConfig = (app: any) => {
  basicConfig.name = app.name;
  basicConfig.version = app.deployment?.version || '1.0.0';
  basicConfig.description = app.description;
  basicConfig.environment = app.deployment?.environment || 'prod';
  basicConfig.region = app.deployment?.region || 'cn-hangzhou';

  // 这里应该从API加载详细配置
  // 暂时使用默认值
};

// 添加环境变量
const addEnvVar = () => {
  const newId = Math.max(...envVars.value.map((v) => v.id), 0) + 1;
  envVars.value.push({
    id: newId,
    key: '',
    value: '',
    description: '',
  });
};

// 删除环境变量
const removeEnvVar = (index: number) => {
  envVars.value.splice(index, 1);
};

// 保存配置
const handleSave = async () => {
  try {
    saving.value = true;

    // 验证表单
    await Promise.all([
      basicFormRef.value?.validate(),
      resourceFormRef.value?.validate(),
    ]);

    // 构建配置数据
    const configData = {
      applicationId: props.application.id,
      basic: { ...basicConfig },
      resources: { ...resourceConfig },
      envVars: envVars.value,
      features: features.value,
      advancedFeatures: advancedFeatures.value,
    };

    // 调用保存API
    // await saveApplicationConfig(configData);

    message.success('配置保存成功');
    emit('saved');
    emit('update:visible', false);
  } catch (error) {
    console.error('保存配置失败:', error);
    message.error('保存配置失败');
  } finally {
    saving.value = false;
  }
};

// 重置配置
const handleReset = () => {
  if (props.application) {
    loadApplicationConfig(props.application);
  }
  message.info('配置已重置');
};

// 取消
const handleCancel = () => {
  emit('update:visible', false);
};
</script>

<template>
  <div class="application-config">
    <a-modal
      :open="visible"
      title="应用配置管理"
      width="900px"
      :footer="null"
      @cancel="handleCancel"
      @update:open="(val) => emit('update:visible', val)"
    >
      <div class="config-container">
        <!-- 配置选项卡 -->
        <a-tabs
          :active-key="activeTab"
          type="card"
          @update:active-key="activeTab = $event"
        >
          <!-- 基础配置 -->
          <a-tab-pane key="basic" tab="基础配置">
            <a-form
              ref="basicFormRef"
              :model="basicConfig"
              :rules="basicRules"
              layout="vertical"
            >
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="应用名称" name="name">
                    <a-input v-model:value="basicConfig.name" disabled />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="应用版本" name="version">
                    <a-input v-model:value="basicConfig.version" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-form-item label="应用描述" name="description">
                <a-textarea
                  v-model:value="basicConfig.description"
                  :rows="3"
                  placeholder="请输入应用描述"
                />
              </a-form-item>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="运行环境" name="environment">
                    <a-select v-model:value="basicConfig.environment">
                      <a-select-option value="dev">开发环境</a-select-option>
                      <a-select-option value="staging">
                        测试环境
                      </a-select-option>
                      <a-select-option value="prod">生产环境</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="部署区域" name="region">
                    <a-select v-model:value="basicConfig.region">
                      <a-select-option value="cn-hangzhou">
                        华东1（杭州）
                      </a-select-option>
                      <a-select-option value="cn-beijing">
                        华北1（北京）
                      </a-select-option>
                      <a-select-option value="cn-shanghai">
                        华东2（上海）
                      </a-select-option>
                      <a-select-option value="cn-shenzhen">
                        华南1（深圳）
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-tab-pane>

          <!-- 资源配置 -->
          <a-tab-pane key="resources" tab="资源配置">
            <a-form
              ref="resourceFormRef"
              :model="resourceConfig"
              :rules="resourceRules"
              layout="vertical"
            >
              <a-card title="计算资源" size="small" style="margin-bottom: 16px">
                <a-row :gutter="16">
                  <a-col :span="8">
                    <a-form-item label="CPU核心数" name="cpu">
                      <a-input-number
                        v-model:value="resourceConfig.cpu"
                        :min="1"
                        :max="32"
                        style="width: 100%"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item label="内存大小(GB)" name="memory">
                      <a-input-number
                        v-model:value="resourceConfig.memory"
                        :min="1"
                        :max="128"
                        style="width: 100%"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item label="存储大小(GB)" name="storage">
                      <a-input-number
                        v-model:value="resourceConfig.storage"
                        :min="10"
                        :max="1000"
                        style="width: 100%"
                      />
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-card>

              <a-card title="网络配置" size="small" style="margin-bottom: 16px">
                <a-row :gutter="16">
                  <a-col :span="12">
                    <a-form-item label="域名" name="domain">
                      <a-input
                        v-model:value="resourceConfig.domain"
                        placeholder="请输入域名"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="端口" name="port">
                      <a-input-number
                        v-model:value="resourceConfig.port"
                        :min="1"
                        :max="65535"
                        style="width: 100%"
                      />
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-card>

              <a-card title="扩展配置" size="small">
                <a-row :gutter="16">
                  <a-col :span="12">
                    <a-form-item label="实例数量" name="replicas">
                      <a-input-number
                        v-model:value="resourceConfig.replicas"
                        :min="1"
                        :max="10"
                        style="width: 100%"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="自动扩缩容" name="autoScale">
                      <a-switch v-model:checked="resourceConfig.autoScale" />
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-card>
            </a-form>
          </a-tab-pane>

          <!-- 环境变量 -->
          <a-tab-pane key="envvars" tab="环境变量">
            <div class="env-vars-container">
              <div class="env-vars-header">
                <h4>环境变量配置</h4>
                <a-button type="primary" size="small" @click="addEnvVar">
                  <template #icon>
                    <IconifyIcon icon="ant-design:plus-outlined" />
                  </template>
                  添加变量
                </a-button>
              </div>

              <a-table
                :columns="envVarColumns"
                :data-source="envVars"
                :pagination="false"
                size="small"
                row-key="id"
              >
                <template #bodyCell="{ column, record, index }">
                  <template v-if="column.key === 'action'">
                    <a-button
                      type="link"
                      size="small"
                      danger
                      @click="removeEnvVar(index)"
                    >
                      删除
                    </a-button>
                  </template>
                </template>
              </a-table>
            </div>
          </a-tab-pane>

          <!-- 功能开关 -->
          <a-tab-pane key="features" tab="功能开关">
            <a-card title="功能模块" size="small" style="margin-bottom: 16px">
              <a-row :gutter="16">
                <a-col :span="8" v-for="feature in features" :key="feature.key">
                  <a-form-item :label="feature.name">
                    <a-switch
                      v-model:checked="feature.enabled"
                      :disabled="feature.required"
                    />
                    <span v-if="feature.required" class="required-tag"
                      >必需</span
                    >
                  </a-form-item>
                </a-col>
              </a-row>
            </a-card>

            <a-card title="高级功能" size="small">
              <a-row :gutter="16">
                <a-col
                  :span="8"
                  v-for="advanced in advancedFeatures"
                  :key="advanced.key"
                >
                  <a-form-item :label="advanced.name">
                    <a-switch v-model:checked="advanced.enabled" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-card>
          </a-tab-pane>
        </a-tabs>

        <!-- 操作按钮 -->
        <div class="config-actions">
          <a-space>
            <a-button @click="handleCancel">取消</a-button>
            <a-button @click="handleReset">重置</a-button>
            <a-button type="primary" @click="handleSave" :loading="saving">
              保存配置
            </a-button>
          </a-space>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
.application-config {
  .config-container {
    .config-actions {
      margin-top: 24px;
      text-align: center;
      border-top: 1px solid #f0f0f0;
      padding-top: 16px;
    }
  }

  .env-vars-container {
    .env-vars-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h4 {
        margin: 0;
      }
    }
  }

  .required-tag {
    margin-left: 8px;
    color: #ff4d4f;
    font-size: 12px;
  }
}
</style>
